package com.ruoyi.web.controller.project;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dgy.common.constants.ProjectConstants;
import com.dgy.project.domain.ProjectApplyFile;
import com.dgy.project.domain.ProjectInfo;
import com.dgy.project.pojo.dto.ProjectApplyListDTO;
import com.dgy.project.pojo.vo.ProjectApplyListVO;
import com.dgy.project.service.IProjectApplyFileService;
import com.dgy.project.service.IProjectInfoService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.dgy.project.domain.ProjectApply;
import com.dgy.project.service.IProjectApplyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目节点Controller
 *
 * @author ccc
 * @date 2025-03-26
 */
@RestController
@RequestMapping("/project/apply")
public class ProjectApplyController extends BaseController
{
    @Autowired
    private IProjectApplyService projectApplyService;

    @Autowired
    private IProjectApplyFileService projectApplyFileService;

    @Autowired
    private IProjectInfoService projectInfoService;

    /**
     * 查询项目申请列表(已提交的)
     */
    @PreAuthorize("@ss.hasPermi('project:Apply:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectApplyListDTO projectApplyListDTO)
    {
        startPage();
        // 只取已经提交的
        List<Integer> applyStatusList = new ArrayList<>();
        applyStatusList.add(1);
        applyStatusList.add(2);
        applyStatusList.add(3);
        projectApplyListDTO.setApplyStatusList(applyStatusList);
        List<ProjectApplyListVO> list = projectApplyService.selectValidApplyList(projectApplyListDTO);
        return getDataTable(list);
    }

    /**
     * 导出项目申请列表(已提交的)
     */
    @PreAuthorize("@ss.hasPermi('project:Apply:export')")
    @Log(title = "项目申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProjectApplyListDTO projectApplyListDTO)
    {
        // 只取已经提交的
        List<Integer> applyStatusList = new ArrayList<>();
        applyStatusList.add(1);
        applyStatusList.add(2);
        applyStatusList.add(3);
        projectApplyListDTO.setApplyStatusList(applyStatusList);
        List<ProjectApplyListVO> list = projectApplyService.selectValidApplyList(projectApplyListDTO);
        ExcelUtil<ProjectApplyListVO> util = new ExcelUtil<ProjectApplyListVO>(ProjectApplyListVO.class);
        util.exportExcel(response, list, "项目申请列表数据");
    }

    /**
     * 查询我的项目申请列表
     */
    @PreAuthorize("@ss.hasPermi('project:Apply:myList')")
    @GetMapping("/myList")
    public TableDataInfo myList(ProjectApplyListDTO projectApplyListDTO)
    {
        startPage();
        // 当前用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        projectApplyListDTO.setCreateBy(loginUser.getUsername());
        List<ProjectApplyListVO> list = projectApplyService.selectValidApplyList(projectApplyListDTO);
        return getDataTable(list);
    }

    /**
     * 导出我的项目申请列表
     */
    @PreAuthorize("@ss.hasPermi('project:Apply:exportMyList')")
    @Log(title = "我的申请列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMyList")
    public void exportMyList(HttpServletResponse response, ProjectApplyListDTO projectApplyListDTO)
    {
        // 当前用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        projectApplyListDTO.setCreateBy(loginUser.getUsername());
        List<ProjectApplyListVO> list = projectApplyService.selectValidApplyList(projectApplyListDTO);
        ExcelUtil<ProjectApplyListVO> util = new ExcelUtil<ProjectApplyListVO>(ProjectApplyListVO.class);
        util.exportExcel(response, list, "项目申请列表数据");
    }

    /**
     * 获取项目申请详细信息（包含申报附件）
     */
    @PreAuthorize("@ss.hasPermi('project:Apply:getInfo')")
    @GetMapping("/getInfo")
    public AjaxResult getInfo(ProjectApply projectApply)
    {
        // 审报记录信息
        ProjectApply apply = projectApplyService.selectProjectApply(projectApply);
        if(ObjectUtil.isNotEmpty(apply)){
            // 申报附件列表
            ProjectApplyFile projectApplyFile = new ProjectApplyFile();
            projectApplyFile.setApplyId(apply.getApplyId());
            List<ProjectApplyFile> fileList = projectApplyFileService.selectprojectApplyFileList(projectApplyFile);
            apply.setProjectApplyFileList(fileList);
        }
        return success(apply);
    }

    /**
     * 保存项目申请
     */
    @PreAuthorize("@ss.hasPermi('project:Apply:save')")
    @Log(title = "项目申请", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody ProjectApply projectApply)
    {
        if(CollUtil.isEmpty(projectApply.getProjectApplyFileList())){
            return error("请上传申报附件");
        }
        return success(projectApplyService.saveProjectApply(projectApply));
    }

    /**
     * 项目申报审核
     */
    @PreAuthorize("@ss.hasPermi('project:Apply:audit')")
    @Log(title = "项目申报审核", businessType = BusinessType.UPDATE)
    @PostMapping("/audit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult audit(@RequestBody ProjectApply projectApply)
    {
        // 查询申请记录
        ProjectApply apply = projectApplyService.selectProjectApplyById(projectApply.getApplyId());
        if(ObjectUtil.isEmpty(apply)){
            return error("申请记录不存在");
        }
        // 变更申报记录审核状态
        projectApplyService.updateProjectApply(projectApply);
        // 变更项目审核状态
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setProjectId(apply.getProjectId());
        projectInfo.setProjectStatus(apply.getApplyStatus());
        // 若审核通过变更项目步骤到下个步骤
        Integer nextStep = apply.getApplyStep() + 1;
        if(ProjectConstants.AUDIT_STATUS_PASS.equals(projectApply.getApplyStatus())
                && ProjectConstants.CONCLUSION_STEP >= nextStep){
            // 变更项目阶段
            projectInfo.setProjectStep(nextStep);
            // 初始化下个阶段的申请（申请状态为待审核）
            ProjectApply nextApply = new ProjectApply();
            nextApply.setProjectId(apply.getProjectId());
            nextApply.setCreateBy(apply.getCreateBy());
            nextApply.setApplyStep(nextStep);
            nextApply.setApplyStatus(ProjectConstants.AUDIT_STATUS_UN_SUBMIT);
            projectApplyService.insertProjectApply(nextApply);
        }
        projectInfoService.updateProjectInfo(projectInfo);
        return success(true);
    }


}
